<template>
	<view class="yp" :style="{ overflow: overflow, height: height }">
		<!-- 导航栏 -->
		<u-navbar title-color="#000" back-icon-color="#000" is-back="true" :background="background" :back-text-style="{ color: '#000' }"
		 back-icon-name="nav-back">
			<view class="navbar-right font-wei600 fo-34 ml10">评论({{ ArticleDetail.CommonTotal }})</view>
			<view class="navbar-right" slot="right">
				<!-- <view class="dot-box right-item fo-black" @click="onPublish">发布</view> -->
			</view>
		</u-navbar>
		<!-- 下拉刷新 -->
		<view class="pullRefresh" ref="pullRefresh" :class="isEnd ? 'transition-Zero5' : ''" :style="{ marginTop: marginTop + 'px' }"
		 @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend">
			<view class="text-center flex ali-end just-cent pb40" style="height: 100px; background-color:#f5f5f5 ;">
				<text class="cuIcon-icloading mr20 fo-40" :class="loadText === '加载中...' ? 'animation-rotate' : ''"></text>
				<text class="fo-gray fo-32">{{ loadText }}</text>
			</view>

			<!-- 占位颜色 -->
			<view style="background-color: #f5f5f5;height: 20rpx;" class="wid1p"></view>
			<!-- 评论区 -->
			<view class="commonBlock flex flex-col padd20 bg-White" @touchmove="commonBlockTouchmove">
				<!-- 头部 -->
				<view class="common-hd flex wid1p just-spa-bet">
					<text class="fo-30">评论区</text>
					<view class="common-hd-right">
						<text class="" :class="SelJson.SortType === 'SortNew' ? 'SelUse' : ''" @click.stop="Sort('SortNew')">最新</text>
						<text class="" :class="SelJson.SortType === 'SortMoreLike' ? 'SelUse' : ''" @click.stop="Sort('SortMoreLike')">最多赞</text>
						<text class="" :class="SelJson.SortType === 'SortHot' ? 'SelUse' : ''" @click.stop="Sort('SortHot')">最热评</text>
					</view>
				</view>

				<template v-if="CommonList.length > 0">
					<!-- 评论卡片 -->
					<view class="CommonCard pt20 pb4 bg-White" v-for="i in CommonList" :key="i._id">
						<!-- 评论卡片-头部 -->
						<view class="Card-hd wid1p flex just-spa-bet ali-cen">
							<view class="flex just-spa-bet ali-cen">
								<image :src="i.UserInfo[0].avatar ? i.UserInfo[0].avatar : 'http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg'"
								 class="yicon-lg radius50p mr20" mode="scaleToFill"></image>
								<view class="info">
									<view class="">{{ i.UserInfo[0].Nickname }}</view>
									<text class="fo-gray fo-20">{{ $tool.friendlyDate(new Date(i.commonTime)) }}</text>
								</view>
							</view>
							<view class="fo-gray" @click.stop="onlike(i)">
								<text class="mr10" :class="i.iSlike ? 'cuIcon-appreciatefill' : 'cuIcon-appreciate'"></text>
								<text>{{ i.likeCount }}</text>
							</view>
						</view>
						<!-- 评论卡片-文字内容 -->
						<view>
							<text class="card-content pl100 mt20" @click="onReply(i)" selectable="true">{{ i.commonValue }}</text>
						</view>
						<!-- 评论卡片-查看更多 -->
						<view class="fo-blue pl100 mt20 inline-block" v-if="i.SecondList.length > 0" @click.stop="onSecondCommon(i)">
							<text class="mr2">{{ i.SecondList.length }}条回复</text>
							<text class="cuIcon-right"></text>
						</view>
						<!-- 评论卡片-底部边框 -->
						<view class="line-gray pl100 mt30"></view>
					</view>
				</template>
				<template v-else>
					<view class="center-center flex flex-col ali-cen">
						<image src="../../static/img/community/noCommon.png" class="yicon-xl"></image>
						<text class="mt20 font-wei600 fo-38">暂无评论</text>
					</view>
				</template>
			</view>

			<!-- 加载更多 -->
			<u-loadmore v-if="CommonList.length >= 10" class="padd20" :status="LoadMoreStatus" icon-type="flower" />
			<!-- 底部占位 -->
			<view style="height: 140rpx; background-color: #fff;"></view>
			<!-- 底部发布评论 -->
			<foot-common ref="FootCommon" :articleId="opt.ArticleId" :ArticleDetail="ArticleDetail" @FreshList="SelCommon('ReFresh')"
			 v-if="!isShow_H5_Mask" @changeCommonLenS='changeCommonLenS'></foot-common>

			<!-- 跳转二级评论弹窗 -->
			<drop-down :isShow_H5_Mask.sync="isShow_H5_Mask" position="bottom" :isMask="true">
				<view slot="content" class="bottom-list">
					<second-common :isShow_H5_Mask.sync="isShow_H5_Mask" :SecondInfo.sync="SecondInfo" :overflow.sync="overflow"
					 @changeSecondCommonLenS='changeSecondCommonLenS'></second-common>
				</view>
			</drop-down>
		</view>
	</view>
</template>

<script>
	let StartScrollX,
		StartScrollY,
		MoveScrollY,
		timer,
		timers, // 防止重复触底
		X_OR_Y_MOVE = null; // 判断是上下滑还是左右滑
	const {
		windowWidth,
		windowHeight
	} = uni.getSystemInfoSync();
	import FootCommon from './conpoment/FootCommon.vue';
	import DropDown from '../public/DropDownPopup';
	import SecondCommon from './SecondCommon.vue';
	import {
		API$SelCommonList,
		API$CommonLike,
		API$SelArticleDetail,
		API$CommonSort
	} from '../../common/API/community.js';
	export default {
		name: '',
		components: {
			FootCommon,
			DropDown,
			SecondCommon
		},
		// #ifdef APP-PLUS
		onBackPress(e) {
			if (e.from === 'backbutton') {
				if (this.isShow_H5_Mask) {
					this.isShow_H5_Mask = false
					return true
				}
			}
		},
		// #endif
		created() {
			// 首次加载启动下拉刷新占位刷新
			this.marginTop = -30;
			this.loadText = '加载中...';

			this.SelCommon();
		},
		onReachBottom() {
			console.log(1111);
		},
		data() {
			return {
				opt: '', // 页面传过来的参数
				isShow_H5_Mask: false, // DropDownPopup是否显示(文件操作栏)
				background: {
					background: '#fff'
				},
				CommonList: [], // 当前文章下的所有评论列表（含1级2级）
				ArticleDetail: {
					CommonTotal: 0
				}, // 文章详细信息
				SecondInfo: {}, // 传给二级评论弹窗 请求接口需要的数据

				CurrentTopPositon: 0,
				loadText: '下拉刷新',
				marginTop: -100,
				isEnd: false,

				overflow: 'scroll', // 自定义界面高度 自滚动
				height: '100vh', // 自定义界面高度 自滚动

				LoadMoreStatus: 'loadmore', // 加载更多状态

				total: '',
				SelJson: {
					SortType: 'SortNew',
					pageNum: 0,
					pageSize: 10
				},

				isLoading: false // 当前是否触底加载中 加载中不可操作
			};
		},
		onLoad(opt) {
			this.opt = opt;
		},
		methods: {
			// 静态添加评论信息
			changeCommonLenS(data){
				console.log(data)
				this.CommonList.unshift(data)
			},
			// 改变几条回复的状态(二级)
			changeSecondCommonLenS(info) {
				this.CommonList.forEach((i, j) => {
					if (info.id === i._id) {
						i.SecondList.push(info.data)
					}
				})
			},
			// 查询评论
			async SelCommon(instruct) {
				let json = {
					articleId: this.opt.ArticleId,
					UserId: this.$pub.getStorageSync('UserInfo')._id
				};
				let {
					code,
					msg,
					data,
					total
				} = await API$SelCommonList(Object.assign(json, JSON.parse(JSON.stringify(this.SelJson))));
				if (code === 200) {
					this.total = total;
					this.CommonList = instruct === 'ReFresh' ? data : this.CommonList.concat(data);
				}
				this.SelArticleDetail();
				this.FreshOk();
				this.isLoading = false; // 结束否触底加载中
				timers = null
			},
			// 查询文章详情信息
			async SelArticleDetail() {
				let SelJson = {
					articleId: this.opt.ArticleId,
					UserId: this.$pub.getStorageSync('UserInfo')._id
				};
				let {
					code,
					msg,
					data
				} = await API$SelArticleDetail(SelJson);
				if (code === 200) {
					this.ArticleDetail = data;
				}
				uni.stopPullDownRefresh();
			},

			// 评论条点赞
			async onlike(e) {
				// 静态改变
				if (e.iSlike) {
					this.$set(e, 'iSlike', false)
					this.$set(e, 'likeCount', e.likeCount - 1)
				} else {
					this.$set(e, 'iSlike', true)
					this.$set(e, 'likeCount', e.likeCount + 1)
				}

				// 接口改变
				let {
					code,
					msg,
					data,
					iSlike
				} = await API$CommonLike({
					_id: e._id, // 这个id是该条评论的id
					UserId: this.$pub.getStorageSync('UserInfo')._id // 这个id是用户的id
				});
				this.$pub.Toast(msg);
			},
			// 跳转第二级评论
			onSecondCommon(e) {
				this.isShow_H5_Mask = true;
				// console.warn('传给二级评论弹窗 请求接口需要的数据:',e)
				this.SecondInfo = e;

				// #ifdef H5
				document.body.style.overflow = 'hidden';
				document.body.style.height = '100%';
				// #endif
				// #ifdef APP-PLUS
				this.overflow = 'hidden';
				// #endif
			},
			// 回复评论
			onReply(e) {
				console.log(e);
				this.$refs.FootCommon.inputFocus({
					_id: e._id, // 这条评论的_id 做二级评论需要的
					Nickname: e.UserInfo[0].Nickname, // 被回复的昵称
					commonValue: e.commonValue // 被回复的内容
				});
			},
			// 排序
			async Sort(type) {
				this.LoadMoreStatus = 'loading';
				this.SelJson.pageNum = 0; // 切换排序要将页码置0
				let linshi = JSON.parse(JSON.stringify(this.SelJson));
				if (linshi.SortType === type) {
					return;
				}
				this.SelJson.SortType = type;
				if (type === 'SortHot') {
					this.$pub.Toast('功能开发中~');
					return;
				}
				let json = {
					articleId: this.opt.ArticleId,
					UserId: this.$pub.getStorageSync('UserInfo')._id
				};

				let {
					code,
					msg,
					data,
					total
				} = await API$SelCommonList(Object.assign(json, JSON.parse(JSON.stringify(this.SelJson))));
				if (code === 200) {
					this.total = total;
					this.CommonList = data;
				}
			},
			// 监控评论节点的触底加载
			commonBlockTouchmove(e) {
				if (this.isLoading) return; // 防止重复触底请求加载
				if (this.CommonList.length < 10) return; // 没满10条不让触底加载
				let views = uni.createSelectorQuery().select('.commonBlock');
				views
					.boundingClientRect(data => {
						// let Computeds = windowHeight - 60 -45 -20 + 20 +100 - 44
						//  750 		- 90		 - 20			= 640
						//  屏幕高度		导航栏+占位	 加载更多高度
						console.log('bottom:', Math.floor(data.top + data.height),windowHeight);
						if (Math.floor(Math.floor(data.top + data.height)) <= windowHeight) {
							this.isLoading = true;
							this.LoadMoreStatus = 'loading';

							if (timers) return
							timers = setTimeout(() => {
								if (this.SelJson.pageNum + 1 > Math.floor(this.total / this.SelJson.pageSize)) return (this.LoadMoreStatus =
									'nomore');
								this.SelJson.pageNum++;
								console.log(this.SelJson.pageNum, this.isLoading)
								this.SelCommon();
								console.log('触底了');
								
							}, 1000)
						}
						// if(Math.floor(data.height) <=  Math.abs((Math.floor(data.top))) +  Math.floor(data.bottom)){}
					})
					.exec();
			},
			/*下拉刷新  封装************************************************************************************************/
			panduan() {
				let views = uni.createSelectorQuery().select('.pullRefresh');
				views
					.boundingClientRect(data => {
						this.CurrentTopPositon = data.top;
					})
					.exec();
			},
			touchstart(e) {
				if (this.overflow === 'hidden') return;

				StartScrollX = e.touches[0].clientX;
				StartScrollY = e.touches[0].clientY;
				this.isEnd = false;
			},
			touchmove(e) {
				if (this.overflow === 'hidden') return;

				this.panduan(MoveScrollY);
				MoveScrollY = e.touches[0].clientY - StartScrollY;
				if (this.CurrentTopPositon >= -56 && MoveScrollY > 0) {
					this.loadText = '下拉刷新';
					// 阻尼系数0.5
					this.marginTop = -100 + MoveScrollY * 0.3;
					if (MoveScrollY > 180) {
						this.loadText = '释放刷新';
					}
				}
			},
			touchend(e) {
				if (this.overflow === 'hidden') return;
				// 下拉强度是180
				if (this.CurrentTopPositon >= -56 && MoveScrollY > 180) {
					this.loadText = '加载中...';

					this.SelJson.SortType = 'SortNew';
					this.SelJson.pageNum = 0;
					this.SelCommon('ReFresh');
				} else {
					this.isEnd = true;
					this.marginTop = -100;
				}

				StartScrollX = null;
				StartScrollY = null;
				MoveScrollY = null;
			},
			// 刷新成功~
			FreshOk() {
				this.isEnd = true;
				this.loadText = '刷新成功~';
				console.log('%c刷新成功', 'color:red');

				this.marginTop = -100;
			}
		}
	};
</script>

<style lang="less" scoped="scoped">
	.yp {
		background-color: #fff;
	}

	.u-demo {
		//height: 200vh;
		height: calc(100% - 44px);
		height: calc(100% - 44px - constant(safe-area-inset-top));
		height: calc(100% - 44px - env(safe-area-inset-top));
	}

	.wrap {
		padding: 24rpx;
	}

	.navbar-right {
		margin-right: 24rpx;
		display: flex;
	}

	.search-wrap {
		margin: 0 20rpx;
		flex: 1;
	}

	.right-item {
		margin: 0 12rpx;
		position: relative;
		color: #ffffff;
		display: flex;
	}

	.message-box {}

	.slot-wrap {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.map-wrap {
		display: flex;
		align-items: center;
		padding: 4px 6px;
		background-color: rgba(240, 240, 240, 0.35);
		color: #fff;
		font-size: 22rpx;
		border-radius: 100rpx;
		margin-left: 30rpx;
	}

	.map-wrap-text {
		padding: 0 6rpx;
	}

	// 当前选中的排序样式
	.SelUse {
		font-weight: 600;
		font-size: 30rpx;
		color: skyblue;
	}

	.common-hd-right {
		text {
			display: inline-block;
			width: 120rpx;
			text-align: center;
		}
	}

	/deep/ .DropDown_bottom {
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
	}
</style>
